//
//  WJMainTabBarView.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/18.
//

import UIKit

protocol WJMainTabBarViewDelegate: AnyObject {
    func mainTabBar(_ tabBar: WJMainTabBarView, didSelectItemAt index: Int)
    func mainTabBarDidSelectAddButton(_ tabBar: WJMainTabBarView)
}

class WJMainTabBarView: UIView {

    weak var delegate: WJMainTabBarViewDelegate?
    
    // 配置属性
    var itemTitles: [String] = [] {
        didSet {
            setupItems()
        }
    }
    
    var itemIcons: [UIImage] = [] {
        didSet {
            setupItems()
        }
    }
    
    var selectedItemIcons: [UIImage] = [] {
        didSet {
            setupItems()
        }
    }
    
    var selectedIndex: Int = 0 {
        didSet {
            updateSelection()
        }
    }
    
    // 外观配置
    var normalColor: UIColor = .red {
        didSet {
            updateItemsAppearance()
        }
    }
    
    var selectedColor: UIColor = .systemBlue {
        didSet {
            updateItemsAppearance()
        }
    }
    
    var itemSpacing: CGFloat = 10 {
        didSet {
            stackView.spacing = itemSpacing
        }
    }
    
    var barHeight: CGFloat = 49 {
        didSet {
            heightConstraint?.constant = barHeight
        }
    }
    
    // 私有属性
    private var stackView = UIStackView()
    private var items: [WJMainTabBarItem] = []
    private var heightConstraint: NSLayoutConstraint?
    
    private lazy var bgImgView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "main_tab_bg")
        
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    private func setupView() {
        backgroundColor = .white
        
        // 添加阴影效果
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOffset = CGSize(width: 0, height: -1)
        layer.shadowOpacity = 0.1
        layer.shadowRadius = 5
        
        addSubview(bgImgView)
        bgImgView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            bgImgView.leadingAnchor.constraint(equalTo: leadingAnchor),
            bgImgView.trailingAnchor.constraint(equalTo: trailingAnchor),
            bgImgView.topAnchor.constraint(equalTo: topAnchor),
            bgImgView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
        
        // 创建 StackView
        stackView.axis = .horizontal
        stackView.distribution = .fillEqually
        stackView.alignment = .fill
        stackView.spacing = itemSpacing
        stackView.translatesAutoresizingMaskIntoConstraints = false
        
        addSubview(stackView)
        
        // 添加约束
        NSLayoutConstraint.activate([
            stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
            stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
            stackView.topAnchor.constraint(equalTo: topAnchor),
            stackView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor)
        ])
        
        heightConstraint = heightAnchor.constraint(equalToConstant: barHeight + safeAreaInsets.bottom)
        heightConstraint?.isActive = true
    }
    
    private func setupItems() {
        items.forEach { $0.removeFromSuperview() }
        items.removeAll()
        let count = min(itemIcons.count, selectedItemIcons.count)
        
        for i in 0..<count {
            let item = WJMainTabBarItem()
            item.icon = itemIcons[i]
            if i < selectedItemIcons.count {
                item.selectedIcon = selectedItemIcons[i]
            }
            
            if i < itemTitles.count {
                item.title = itemTitles[i]
            }

            item.tag = i
            item.isSelected = (i == selectedIndex)
            item.addTarget(self, action: #selector(itemTapped(_:)), for: .touchUpInside)
            
            stackView.addArrangedSubview(item)
            items.append(item)
        }
        
        updateItemsAppearance()
    }
    
    private func updateItemsAppearance() {
        for (index, item) in items.enumerated() {
            item.normalColor = normalColor
            item.selectedColor = selectedColor
            item.isSelected = (index == selectedIndex)
        }
    }
    
    private func updateSelection() {
        for (index, item) in items.enumerated() {
            item.isSelected = (index == selectedIndex)
        }
    }
    
    @objc func itemTapped(_ sender: WJMainTabBarItem) {
        let newIndex = sender.tag
        guard newIndex != selectedIndex else { return }
        
        if newIndex != 1 {
            items.forEach { $0.isSelected = false }
            sender.isSelected = true
            selectedIndex = newIndex
            delegate?.mainTabBar(self, didSelectItemAt: newIndex)
        } else {
            delegate?.mainTabBarDidSelectAddButton(self)
        }
    }
    
    override func safeAreaInsetsDidChange() {
        super.safeAreaInsetsDidChange()
        heightConstraint?.constant = barHeight + safeAreaInsets.bottom
    }

}
